package com.lanyou.cook.camel.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.component.quartz2.QuartzComponent;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.log4j.Logger;

import com.lanyou.cook.camel.entity.Ftp;

/**
 * 负责统一创建、存储CamelContext的工厂
 * 
 * @author ly-lihailang
 *
 */
public class CamelFactory {
	private static Logger logger = Logger.getLogger(CamelFactory.class);
	/**
	 * 以map存储创建的CamelContext，key：接口编号；value：CamelContext对象（可以改为redis存储）
	 */
	public static Map<String, CamelContext> camelMap = new HashMap<String, CamelContext>();

	/**
	 * zookeeper选举Leader的结果，如果是将值改为true
	 */
	public static boolean isLeader = false;
	
	/**
	 * 存放FTP到Map减少数据库访问量
	 */
	public static Map<String, Ftp> ftpMap = new HashMap<String, Ftp>();

	/**
	 * 路由执行状态
	 */
//	public static Map<String, Map<String, String>> routeMap = new HashMap<String, Map<String, String>>();

	/**
	 * @param camelId
	 *            接口编号
	 * @return 根据接口编号创建的CamelContext对象
	 */
	public static synchronized CamelContext ctreatCamel(String camelId) {
		// 判断是否以后该接口的CamelContext对象
		if (camelMap.get(camelId) != null) {// 已存在，则直接返回该对象
			return camelMap.get(camelId);
		} else {// 不存在则创建
			CamelContext camelContext = new DefaultCamelContext();
			logger.info("[CamelFactory.ctreatCamel]:新创建---" + camelId);
			camelContext.setTracing(true);
			// 判断是否有ftp,quartz2路由的模板，没有则添加
			if (camelContext.getComponent("ftp") == null) {
				camelContext.addComponent("ftp", new FtpComponentChild());
			}
			if (camelContext.getComponent("quartz2") == null) {
				camelContext.addComponent("quartz2", new QuartzComponent());
			}
			// 将创建好的camelContext保存
			camelMap.put(camelId, camelContext);
//			routeMap.put(camelId, new HashMap<String, String>());
			return camelContext;
		}
	}

	/**
	 * @param camelId
	 *            接口编号
	 * @return map 中的CamelContext
	 */
	public static CamelContext getCamel(String camelId) {
		return camelMap.get(camelId);
	}

}
